package io.kimmking.rpcfx.client.netty_temp;
  
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
@Slf4j
@ChannelHandler.Sharable
public class HttpClientInboundHandler extends ChannelInboundHandlerAdapter {

    private ChannelHandlerContext ctx;
    private ChannelPromise promise;
    private String response;
    public synchronized String sendMessage(String message) throws URISyntaxException, ExecutionException, InterruptedException {
        while (ctx == null) {
            try {
                TimeUnit.MILLISECONDS.sleep(1);
            } catch (InterruptedException e) {
                log.error("等待ChannelHandlerContext实例化过程中出错",e);
            }
        }

        response = null;
        promise = ctx.newPromise();
        URI uri = new URI("http://127.0.0.1:8844");
        DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
                uri.toASCIIString(), Unpooled.wrappedBuffer(message.getBytes(StandardCharsets.UTF_8)));
        ctx.writeAndFlush(request);
        promise.get();
        return response;
    }

    public void write(String msg) throws URISyntaxException {
        URI uri = new URI("http://127.0.0.1:8844");
        DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
                uri.toASCIIString(), Unpooled.wrappedBuffer(msg.getBytes(StandardCharsets.UTF_8)));
        ctx.writeAndFlush(request);
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.ctx  = ctx;
    }
    @Override  
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if (msg instanceof HttpResponse)   
        {  
            HttpResponse response = (HttpResponse) msg;  
            //System.out.println("CONTENT_TYPE:" + response.headers().get(HttpHeaders.Names.CONTENT_TYPE));

        }  
        if(msg instanceof HttpContent)  
        {  
            HttpContent content = (HttpContent)msg;  
            ByteBuf buf = content.content();
            response = buf.toString(CharsetUtil.UTF_8);
            promise.setSuccess();
            buf.release();
        }
    }  
}